package com.liuyun.aes;

import lombok.SneakyThrows;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;

/**
 * AES_CBC：引入IV（类似盐值）
 * <p>
 * Copyright: (C), 2020/12/30 23:49
 * <p>
 * <p>
 * Company Information & Data Security Solutions Co., Ltd.
 *
 * @author LiuYun liujw@idss-cn.com
 * @version 1.0
 */
public class AES_CBC {

    /**
     * 算法和模式
     */
    private static final String CIPHER_ALGORITHM_CBC = "AES/CBC/PKCS5Padding";
    /**
     * 密钥所对应的算法
     */
    private static final String KEY_ALGORITHM = "AES";

    /**
     * 默认随机密钥
     */
    private static byte[] KEY_16_BYTE = initKey();
    /**
     * 默认IV矩阵（盐值）
     */
    private static byte[] IV_16_BYTE = initKey();

    /**
     * 生成密钥
     *
     * @return
     * @throws Exception
     */
    @SneakyThrows
    public static byte[] initKey() {
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        kg.init(128);
        SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }

    /**
     * 加密
     *
     * @param data 明文的字节数组
     * @param key  密钥的字节数组
     * @param iv   16个字节的矩阵，类似盐值的作用
     * @return 密文的字节数组
     */
    @SneakyThrows
    public static byte[] encrypt(byte[] data, byte[] key, byte[] iv) {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
        Key k = new SecretKeySpec(key, KEY_ALGORITHM);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, k, paramSpec);
        return cipher.doFinal(data);
    }

    /**
     * 解密
     *
     * @param bytes 密文的字节数组
     * @param key   密钥的字节数组
     * @param iv    16个字节的矩阵，类似盐值的作用
     * @return 明文的字节数组
     */
    @SneakyThrows
    public static byte[] decrypt(byte[] bytes, byte[] key, byte[] iv) {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
        Key k = new SecretKeySpec(key, KEY_ALGORITHM);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, k, paramSpec);
        return cipher.doFinal(bytes);
    }

    /**
     * 加密
     *
     * @param data 明文字符串
     * @param key  密钥的字节数组
     * @param iv   16个字节的矩阵，类似盐值的作用
     * @return 密文base64编码字符串
     */
    @SneakyThrows
    public static String encodeToBase64String(String data, byte[] key, byte[] iv) {
        return Base64.getEncoder().encodeToString(encrypt(data.getBytes(), key, iv));
    }

    /**
     * 解密
     *
     * @param data 密文字符串
     * @param key  密钥的字节数组
     * @param iv   16个字节的矩阵，类似盐值的作用
     * @return 明文base64编码字符串
     */
    @SneakyThrows
    public static String decodeFromBase64String(String data, byte[] key, byte[] iv) {
        byte[] bytes = Base64.getDecoder().decode(data);
        return new String(decrypt(bytes, key, iv));
    }


    /**
     * 加密
     *
     * @param data 明文字符串
     * @return 密文base64编码字符串
     */
    @SneakyThrows
    public static String encodeToBase64String(String data) {
        return Base64.getEncoder().encodeToString(encrypt(data.getBytes(), KEY_16_BYTE, IV_16_BYTE));
    }

    /**
     * 解密
     *
     * @param data 密文字符串
     * @return 明文base64编码字符串
     */
    @SneakyThrows
    public static String decodeFromBase64String(String data) {
        byte[] bytes = Base64.getDecoder().decode(data);
        return new String(decrypt(bytes, KEY_16_BYTE, IV_16_BYTE));
    }


    public static void main(String[] args) {
        byte[] key = AES_CBC.initKey();
        byte[] iv = {0x01, 0x23, 0x45, 0x67, 0x89 - 0xFF, 0xAB - 0xFF, 0xCD - 0xFF, 0xEF - 0xFF,
                0x01, 0x23, 0x45, 0x67, 0x89 - 0xFF, 0xAB - 0xFF, 0xCD - 0xFF, 0xEF - 0xFF};
        String content = "areful1997";
        String cipher = AES_CBC.encodeToBase64String(content, key, iv);
        System.out.println(cipher);

        String plain = AES_CBC.decodeFromBase64String(cipher, key, iv);
        System.out.println(plain);

        // 默认密钥和默认IV进行加解密
        String encode = encodeToBase64String(content);
        System.out.println(encode);
        String decode = decodeFromBase64String(encode);
        System.out.println(decode);
    }
}
